package cn.good.user.service;

import cn.good.pojo.User;
import cn.good.service.TokenService;
import cn.good.utils.*;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * token业务类
 */
@Component
@Service(interfaceClass = TokenService.class)
public class RPCTokenServiceImpl implements TokenService {

    private final String TOKEN_PRIXE="token:";
    @Resource
    private RedisUtil redisUtil;
    /**
     * 生成token
     * @param user
     * @return
     * @throws Exception
     */
    @Override
    public String createToken(User user) throws Exception {

        StringBuilder sb = new StringBuilder(TOKEN_PRIXE);

        sb.append(MD5.getMd5(user.getUserCode(),32));

        sb.append("-"+user.getId());

        sb.append("-"+ new SimpleDateFormat(Constant.TOKEN_DATE_FORMAT).format(new Date()));

        String token = sb.toString();

        redisUtil.set(token,new Long(Constant.TOKEN_VALID_TIME).intValue(), JSON.toJSONString(user));

        return token;
    }

    /**
     * 注销
     * @param token
     * @return
     * @throws Exception
     */
    @Override
    public Boolean logOut(String token) throws Exception {
        if(token==null || token.equals("")){
            throw new Exception("参数错误");
        }
        if(redisUtil.exist(token)){
            redisUtil.delete(token);
        }else {
            throw new Exception("token不存在！");
        }
        return true;
    }
}
